package com.example.xihuashoujiduan.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.xihuashoujiduan.R
import com.example.xihuashoujiduan.base.BaseActivity
import com.example.xihuashoujiduan.databinding.ActivitySaomaBinding
import com.example.xihuashoujiduan.viewmodel.Mainviewmodel
import com.king.zxing.CaptureHelper
import com.king.zxing.DecodeFormatManager
import com.king.zxing.OnCaptureCallback
import com.king.zxing.camera.CameraManager
import com.king.zxing.camera.FrontLightMode

class SaomaActivity :BaseActivity<Mainviewmodel, ActivitySaomaBinding>(R.layout.activity_saoma),
    OnCaptureCallback {

var captureHelper: CaptureHelper? = null
    override fun initView() {
            binding.fanhui.setOnClickListener {
                finish()
            }

        if (isAndroid13()) {

            Toast.makeText(this, "当前系统是大于安卓 13 版本api${Build.VERSION.SDK_INT}", Toast.LENGTH_SHORT).show()
            checkAndRequestAndroid13Permissions()
        } else {
            Toast.makeText(this, "当前系统是低于安卓 13 版本api${Build.VERSION.SDK_INT}", Toast.LENGTH_SHORT).show()
            checkAndRequestOldPermissions()
        }
        initQRConfig()

    }
    fun isAndroid13(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
    }


    override fun dataObservese() {

    }

    private fun checkAndRequestAndroid13Permissions() {
        val permissionsToRequest = arrayOf(
            Manifest.permission.CAMERA
        )

        val allPermissionsGranted = permissionsToRequest.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }

        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, permissionsToRequest, 101)
        } else {
            proceedAfterPermissionsGranted()
        }
    }
    private fun checkAndRequestOldPermissions() {
        val permissionsToRequest = arrayOf(
            Manifest.permission.CAMERA
        )

        val allPermissionsGranted = permissionsToRequest.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }

        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, permissionsToRequest, 101)
        } else {
            proceedAfterPermissionsGranted()
        }
    }
    private fun proceedAfterPermissionsGranted() {


        val countdownTimer = object : CountDownTimer(2000, 1000) {
            override fun onTick(millisUntilFinished: Long) {

            }

            override fun onFinish() {


            }
        }

        countdownTimer.start()


    }
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 101) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                proceedAfterPermissionsGranted()
            } else {
                finish()
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }
    private fun initQRConfig(){
        captureHelper = CaptureHelper(this, binding.svPreview, binding.vfv, null)
        captureHelper?.setOnCaptureCallback(this)
        captureHelper?.decodeFormats(DecodeFormatManager.QR_CODE_FORMATS)
            ?.supportAutoZoom(true) // 自动缩放
            ?.fullScreenScan(true) // 全屏扫码识别
            ?.supportLuminanceInvert(true) // 是否支持识别反色码，黑白颜色反转，开启提高识别效率
            ?.continuousScan(true) // 开启连续扫描
            ?.autoRestartPreviewAndDecode(false) // 连续扫描开启情况下，取消自动继续扫描，自己处理完后调用restartPreviewAndDecode()
            ?.playBeep(true) // 播放beep声音
            ?.supportZoom(true) // 支持双指缩放
            ?.frontLightMode(FrontLightMode.OFF) // 默认关闭闪光灯
            ?.setOnCaptureCallback(this) // 设置回调
            ?.onCreate()
        val cameraManager: CameraManager = captureHelper!!.cameraManager
        cameraManager.setOnTorchListener { torch: Boolean ->
            binding.tvTorch.isSelected = torch
            binding.tvTorch.text = if (torch) "关闭照明" else "打开照明"
        }
        binding.tvTorch.setOnClickListener(View.OnClickListener {
            cameraManager.setTorch(
                !binding.tvTorch.isSelected
            )
        })
        binding.tvTorch.post(Runnable { this.updateScanFrameLocation() })
    }

    private fun updateScanFrameLocation() {
        //(327+184)/2-184
     //   binding.vfv.setPadding(0, 0, 0, Utils.dp2px(this, 71))
        binding.vfv.scannerStart = 0 // 动态改变padding时，需要设置该值为0，以触发在onDraw中对其的重新赋值
    }

    override fun onResultCallback(result: String?): Boolean {
        if(result!=null){
            val intent = Intent(this,SaomajiaguoActivity::class.java)
            intent.putExtra("result",result)
            Log.e("扫码结果",result)
            startActivity(intent)
        }

        //Toast.makeText(this,result,Toast.LENGTH_SHORT).show()
        return true
    }
    override fun onResume() {
        //注意在生命周期的captureHelper设置，否则可能出现无法扫描的问题
        captureHelper?.onResume()
        super.onResume()
    }

    override fun onPause() {
        captureHelper?.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        captureHelper?.onDestroy()
        super.onDestroy()
    }
}